/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ManagedBean;

import au.com.bytecode.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.List;
import mdsj.Data;
import mdsj.MDSJ;
import prefuse.Visualization;
import prefuse.data.Graph;
import prefuse.data.Table;

/**
 *
 * @author ardmello
 */
@Named(value = "importCSV")
@SessionScoped
public class ImportCSV implements Serializable {

    private String urlCSV;
    private CSVReader reader;
    private Visualization vis = new Visualization();
    private double[][] matrix;
    private double[][] distanceMatrix;
    private double[][] mdsMatrix;

    /**
     * Creates a new instance of ImportCSV
     */
    public ImportCSV() {
    }

    public static Table getDataTable(double[][] m) {
        Table tb = new Table(m.length, m[0].length);
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m[i].length; j++) {
                tb.set(i, j, m[i][j]);
            }
        }
        return tb;
    }

    public static Graph getGraph(double[][] m) {
        Table tb = getDataTable(m);
        Graph gh = new Graph(tb, false);
        for (int i = 0; i < tb.getColumnCount(); i++) {
            for (int j = 0; j < tb.getRowCount(); j++) {
                // Insere arestas entre cada um dos elementos
                if (i != j) {
                    gh.addEdge(i, j);
                }
            }
        }
        return gh;
    }

    private void setVisualziation(Graph g) {
        
    }

    public String getUrlCSV() {
        return urlCSV;
    }

    public void setUrlCSV(String urlCSV) throws FileNotFoundException {
        this.urlCSV = urlCSV;
        this.reader = new CSVReader(new FileReader(urlCSV), ';');
    }

    public void loadCSV() throws IOException, NumberFormatException {
        // readAll retorna uma lista de vetores do tipo String
        List<String[]> lines = reader.readAll();
        // declara matrix com o tamanho da lista (lines.size) e o tamanho do 
        // vetor do primeiro componente da lista (lines.get(0)).
        matrix = new double[lines.size()][lines.get(0).length];

        for (int i = 0; i < lines.size(); i++) {
            for (int j = 0; j < lines.get(i).length; j++) {
                matrix[i][j] = Double.valueOf(lines.get(i)[j]);
            }
        }

    }

    public double[][] getDistanceMatrix() {
        distanceMatrix = Data.distanceMatrix(matrix);
        return distanceMatrix;
    }

    public double[][] getMdsMatrix() {
        mdsMatrix = MDSJ.classicalScaling(matrix, 3);
        return mdsMatrix;
    }
}
